package dawn.util;

import java.util.Calendar;
import java.util.TimeZone;

public class TimeUtil {

    public static final long A_Day_Millis = 24 * 60 * 60 * 1000;
    public static final long A_Minute_Millis = 1 * 60 * 1000;
    public static final long A_Hour_Millis = 60 * 60 * 1000;
    public static final long Five_Minute_Millis = 5 * 60 * 1000;
    private static final long TIME1970;

    static {
        TIME1970 = TimeZone.getDefault().getOffset(0);
    }

    /**
     * 判断两个时间戳是否同一个五分钟内
     * 
     * @return
     */
    public static boolean isSameFiveMinute(long time1, long time2) {
        return time1 / Five_Minute_Millis == time2 / Five_Minute_Millis;
    }

    /**
     * 判断两个时间戳是否同一天
     * 
     * @return
     */
    public static boolean isSameDay(long time1, long time2) {
        return (time1 + TIME1970) / A_Day_Millis == (time2 + TIME1970)
                / A_Day_Millis;
    }

    /**
    * 判断两个时间戳是否同一个小时
    * 
    * @return
    */
    public static boolean isSameHour(long time1, long time2) {
        return time1 / A_Hour_Millis == time2 / A_Hour_Millis;
    }

    /**
     * 计算当前时间和传入的参数相差的分钟数, 不满一分钟算一分钟
     * 
     * @param startTime
     * @return
     */
    public static long calculateMinutes(long endTime, long startTime) {
        long interval = Math.abs((endTime - startTime) / A_Minute_Millis);
        if ((endTime - startTime) % A_Minute_Millis != 0) {
            interval += 1;
        }
        return interval;
    }

    /**
     * 计算当前时间和传入的参数相差的天数
     * 
     * @param time
     * @return 同一天或者是未来的时间返回：0
     */
    public static long calculateDays(long time) {
        // 将下面的 理解成 yyyy-MM-dd 00：00：00 更好理解点
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 0);
        long today = cal.getTimeInMillis();
        if ((today - time) > 0 && (today - time) <= A_Day_Millis) {
            return (today - time) / A_Day_Millis + 1;
        } else if ((today - time) <= 0) { // 至少是今天
            return 0;
        } else { // 至少是前天
            return (today - time) / A_Day_Millis + 1;
        }
    }

    public static void main(String[] args) {

        System.out.println(calculateMinutes(123456789L, 123456789L - 3 * 1000));
    }
}
